var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const {JWTconfig} = require('./config'); // 引入配置文件

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var loginRouter = require('./routes/login'); // 引入登录路由
const { expressjwt: expressJwt } = require('express-jwt');

var {formatDates} = require('./common/utils'); // 引入日期格式化中间件
var cors = require('cors');
var responseFormatter = require('./common/responseFormatter'); // 引入响应格式化中间件

var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(cors()); // 使用 CORS 中间件

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// 自定义中间件
app.use(formatDates); // 使用日期格式化中间件
app.use(responseFormatter); // 使用响应格式化中间件


// 使用 express-jwt 中间件进行 token 验证
app.use(
  expressJwt({
    secret: JWTconfig.jwtSecretKey, // 替换为你的密钥
    algorithms: ['HS256'], // 使用的算法
  }).unless({
    path: ['/login','/login/register'], // 不需要验证的路径
  })
);

// 路由模块
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/login', loginRouter); // 使用登录路由


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
